﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SCFHS.Code;
using SCFHS.Data;
using System.Configuration;
using System.IO;

namespace SCFHS.Views
{
    public partial class OrderInstruction : SysBase
    {
        #region Definitions

        #endregion

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) { BindDropDownControls(); }

            string orderID = string.Empty;
            if (Request.QueryString["orderID"] != null)
                orderID = Request.QueryString["orderID"] as string;

            if (!string.IsNullOrEmpty(orderID) && !IsPostBack)
            {
                GetOrder(int.Parse(orderID));
            }

        }

        protected void btnNextToOrder_Click(object sender, EventArgs e)
        {

            Order order = controller.SelectMainOrderInfo(txtOrderNumberToSearch.Text);

            if (order == null)
            {
                lblMessage.Text = Messages.NoOrderFound;
                lblMessage.CssClass = "error";
                return;
            }

            if (order.orderState == Code.OrderStates.Printed)
                order = controller.SelectFullOrderInfo(order.orderID, true, true, true, true);
            else
            {
                lblMessage.Text = Messages.ProceudProcessField;
                lblMessage.CssClass = "error";
                return;
            }

            lblMessage.Text = "";
            mView.ActiveViewIndex = 1;
            BindOrderInfo(order);
        }

        protected void drp_DataBound(object sender, EventArgs e)
        {
            DropDownList drp = ((DropDownList)sender);
            drp.Items.Insert(0, new ListItem("يرجي الإختيار من القائمة", "-1"));
        }

        #endregion

        #region Helper Methods
        void BindOrderInfo(Order order)
        {
            txtpersonName.Text = order.personName;
            txtOrderNumber.Text = order.orderNumber;
            txtDate.Text = order.CreationDate.ToShortDateString();
            hdfOrderNo.Value = order.orderID.ToString();
            txtSubject.Text = order.orderSubject;
            txtClass.Text = order.orderClassificationNumber;
            drpNationality.SelectedValue = order.personNationality.ToString();
            rdBirthPlace.SelectedValue = order.personBirthPlace.ToString();
            drpCurrenCity.SelectedValue = order.personCurrentResidencePlace.ToString();
            rdSecondrySchool.SelectedValue = order.personHighSchoolPlace.ToString();
            txtIDNo.Text = order.personIDNumber;
            rdIDType.SelectedValue = order.personIDType.ToString();
            txtWorkPlace.Text = order.workPlaceName;
            rdWorkType.SelectedValue = order.workPlaceType.ToString();

            BindRequests(order);
            BindSummery(order);
            BindAttachments(order);
        }

        Instructions GetDataFromControls()
        {
            Instructions instruction = new Instructions();
            instruction.instructionAuthority = txtAuthorityOf.Text;
            instruction.instruction = txtInstruction.Text;
            instruction.transferTo = txtForwardTo.Text;
            instruction.transferReason = txtForwardReason.Text;
            instruction.SubmitTimestamp = controller.ConvertDate(txtForwardDate.Text);
            instruction.orderID = int.Parse(hdfOrderNo.Value);
            return instruction;
        }

        void GetOrder(int orderID)
        {
            order = controller.SelectFullOrderInfo(orderID, true, true, true, true);
            if (order == null)
            {
                lblMessage.Text = "عفوا رقم الطلب غير صحيح";
                lblMessage.CssClass = "error";
                return;
            }
            if (order.orderState == Code.OrderStates.Printed)
            {
                lblMessage.Text = "";
                mView.ActiveViewIndex = 1;
                BindOrderInfo(order);
            }
            else
            {
                lblMessage.Text = Messages.ProceudProcessField;
                lblMessage.CssClass = "error";
                return;
            }
        }

        #endregion

        #region Data Methods


        void BindDropDownControls()
        {
            drpCurrenCity.DataSource = controller.ListCities();
            drpCurrenCity.DataValueField = "ID";
            drpCurrenCity.DataTextField = "Name";
            drpCurrenCity.DataBind();

            drpNationality.DataSource = controller.ListNationalities();
            drpNationality.DataValueField = "ID";
            drpNationality.DataTextField = "Name";
            drpNationality.DataBind();

        }

        void BindSummery(Order order)
        {
            grdSummery.DataSource = order.orderSummeryPoints;
            grdSummery.DataBind();
        }

        void BindRequests(Order order)
        {
            grdRequest.DataSource = order.orderRequestPoints;
            grdRequest.DataBind();
        }

        void BindAttachments(Order order)
        {
            grdAttachments.DataSource = order.orderAttachmentPoints;
            grdAttachments.DataBind();
        }
        #endregion

        protected void btnUpdateOrder_Click(object sender, EventArgs e)
        {
            Instructions instruction = GetDataFromControls();
            instruction.isFinalInstruction = false;

            //Insert instruction
            bool result = controller.AddOrderInstruction(instruction);
            if (result)
            {
                //Update order state
                result = controller.UpdateOrderStates(instruction.orderID, OrderStates.WaitingFollowUp, user.userID);
                if (result)
                {
                    mView.ActiveViewIndex = 0;
                    txtOrderNumberToSearch.Text = "";
                    lblMessage.Text = Messages.InstructionAddSuccess;
                    lblMessage.CssClass = "info";
                    return;
                }
            }

            lblMessage.Text = Messages.InstructionAddFail;
            lblMessage.CssClass = "error";
        }

        protected void btnSaveAndClose_Click(object sender, EventArgs e)
        {
            Instructions instruction = GetDataFromControls();
            instruction.isFinalInstruction = true;

            //Insert instruction
            bool result = controller.AddOrderInstruction(instruction);
            if (result)
            {
                //Update order state
                result = controller.UpdateOrderStates(instruction.orderID, OrderStates.InstructionsAndDone, user.userID, isClosed: true);
                if (result)
                {
                    mView.ActiveViewIndex = 0;
                    txtOrderNumberToSearch.Text = "";
                    lblMessage.Text = Messages.InstructionAddSuccess;
                    lblMessage.CssClass = "info";
                    return;
                }
            }

            lblMessage.Text = Messages.InstructionAddFail;
            lblMessage.CssClass = "error";

        }

        protected void btnUploadOrder_Click(object sender, EventArgs e)
        {
            string uploadFolder = ConfigurationManager.AppSettings["UploadPath"].ToString();
            if (string.IsNullOrEmpty(uploadFolder))
            {
                lblMessage.Text = Messages.UploadFolderNotDefined;
                lblMessage.CssClass = "error";
                return;
            }
            string uploadFolderPath = Server.MapPath(uploadFolder) + "\\";
            string fullPath = string.Empty;
            string newFileName = string.Empty;
            string dublicateNewFileName = string.Empty;

            if (!fuOrderSoftcopy.HasFile)
            {
                lblUploadMessage.Text = Messages.UploadNoFile;
                lblUploadMessage.CssClass = "error";
                return;
            }
            try
            {
                newFileName = hdfOrderNo.Value + Path.GetExtension(fuOrderSoftcopy.FileName);
                newFileName = AttachmentsType.OrderSoftCopy.ToString() + "-" + newFileName;
                fullPath = uploadFolderPath + newFileName;
                int count = 0;
                while (File.Exists(fullPath))
                {
                    count++;
                    dublicateNewFileName = "({0})" + newFileName;
                    dublicateNewFileName = string.Format(dublicateNewFileName, count.ToString());
                    fullPath = uploadFolderPath + dublicateNewFileName;
                }

                fuOrderSoftcopy.PostedFile.SaveAs(fullPath);
            }
            catch (Exception)
            {
                throw;
            }
            if (!string.IsNullOrEmpty(dublicateNewFileName))
                newFileName = dublicateNewFileName;
            bool result = controller.AddAttachmentToOrder(int.Parse(hdfOrderNo.Value), newFileName, (int)AttachmentsType.OrderSoftCopy, user.userID);

            if (!result)
            {
                lblUploadMessage.Text = Messages.UploadFail;
                lblUploadMessage.CssClass = "error";
                return;
            }

            lblUploadMessage.Text = Messages.UploadSuccess;
            lblUploadMessage.CssClass = "info";
        }
    }
}